package com.zlcao.plugins.arkcompilersupport

import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogBuilder
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.CheckBoxList
import com.intellij.ui.components.JBCheckBox
import com.intellij.ui.components.JBScrollPane
import com.intellij.ui.layout.selected
import java.awt.Desktop
import java.awt.Dimension
import java.io.File
import java.io.IOException
import javax.swing.JCheckBox

class ArkCompilerCacheCleanAction : AnAction() {

    companion object {
        val DELETE_FILE_TYPES = arrayOf("js", "map", "js.map")
        val DELETE_TIP_DIALOG_SIZE = Dimension(320, 180)
    }

    /**
     * 待删除的文件列表，实际删除取决于用户选中
     */
    private val pendingDeleteFiles = mutableListOf<VirtualFile>()

    override fun actionPerformed(e: AnActionEvent) {
        pendingDeleteFiles.clear()
        // 获取右键点击的文件或文件夹
        val selectedFiles = e.getData(com.intellij.openapi.actionSystem.CommonDataKeys.VIRTUAL_FILE_ARRAY)
        if (selectedFiles != null) {
            for (file in selectedFiles) {
                // 调用将文件移动到系统回收站的方法
                collectDeleteFiles(file)
            }
            // 显示对话框
            e.project?.also {project ->
                showDeleteConfirmDialog(project) {list ->
                    // 删除文件到回收站
                    moveToTrash(project, list)
                    // 刷新项目
                    e.project?.projectFile?.refresh(false, true)
                }
            }
        }
    }

    /**
     * 删除文件确认框
     * @param confirmCallback 确认回调，参数为选中待删除的文件
     */
    private fun showDeleteConfirmDialog(p: Project, confirmCallback: ((selectedFiles: List<VirtualFile>) -> Unit)?) {
        if (pendingDeleteFiles.isEmpty()) {
            Messages.showMessageDialog(p, "请选择删除文件.", "提示", Messages.getInformationIcon())
            return
        }
        val checkboxList = CheckBoxList<VirtualFile>()
        pendingDeleteFiles.forEach {
            checkboxList.addItem(it, it.path, true)
        }
        // 默认选中
//        pendingDeleteFiles.forEach {
//            checkboxList.setItemSelected(it, true)
//        }
        val scrollPane = JBScrollPane(checkboxList).apply {
            minimumSize = DELETE_TIP_DIALOG_SIZE
        }
        val builder = DialogBuilder(p)
        builder
            .title("放到回收站")
            .centerPanel(scrollPane)
            .setPreferredFocusComponent(checkboxList)
        builder.show().also { result ->
            if (result == DialogWrapper.OK_EXIT_CODE) {
                pendingDeleteFiles.filter {
                    checkboxList.isItemSelected(it)
                }.also { selectedFiles ->
                    // 处理用户点击“OK”按钮的逻辑
                    confirmCallback?.invoke(selectedFiles)
                }
            }
        }

    }

    private fun isDeletingFile(file: VirtualFile): Boolean {
        return DELETE_FILE_TYPES.contains(file.extension)
    }

    private fun collectDeleteFiles(file: VirtualFile) {
        if (file.isDirectory) {
            // 如果是目录，获取目录下所有文件
            val files: Array<VirtualFile>? = file.children
            if (files != null) {
                for (childFile in files) {
                    // 递归移动子文件或子目录
                    collectDeleteFiles(childFile)
                }
            }
        }
        // 如果是待删除文件，加入列表
        if (isDeletingFile(file)) {
            pendingDeleteFiles.add(file)
            return
        }
    }

    // 将文件移动到系统回收站
    private fun moveToTrash(p: Project, list: List<VirtualFile>) {
        if(list.isEmpty()) {
            Messages.showMessageDialog(p, "请选择删除文件.", "提示", Messages.getInformationIcon())
        }
        list.forEach {
            moveToTrash(it)
        }
    }

    private fun moveToTrash(file: VirtualFile) {
        try {
            if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.MOVE_TO_TRASH)) {
                Desktop.getDesktop().moveToTrash(File(file.path))
            } else {
                Messages.showMessageDialog(
                    null,
                    "Moving to trash is not supported on this platform.",
                    "Error",
                    Messages.getErrorIcon()
                )
            }
        } catch (e: IOException) {
            e.printStackTrace()
            Messages.showMessageDialog(
                null,
                "Error moving file to trash: ${e.message}",
                "Error",
                Messages.getErrorIcon()
            )
        }
    }
}

